<!-- sticky 固钉 -->
<template>
  <div class="sticky" :style="renderStyle">
    <slot name="content"></slot>
  </div>
</template>

<script lang="ts" setup>
import {defineProps, nextTick, reactive, watch, withDefaults} from 'vue';

/** props */
interface StickyPanelProps {
  // 指定元素
  dom: any,
  // 是否与 dom 齐高
  isTop?: boolean,
  // 是否与 dom 齐底
  isBottom?: boolean,
  // 距离dom的高度
  top?: string,
  // 距离dom的右距离
  right?: string,
  // 距离dom的下距离
  bottom?: string,
  // 距离dom的左距离
  left?: string,
}

/** 钩子参数默认值 */
const props = withDefaults(defineProps<StickyPanelProps>(), {
  dom: document.body,
  isTop: true,
});
let renderValues: StickyPanelProps = reactive({
      dom: props.dom,
      isTop: props.isTop,
      isBottom: props.isBottom,
      top: props.top,
      right: props.right,
      bottom: props.bottom,
      left: props.left
    }),
    renderStyle = {
      top: renderValues.top,
      right: renderValues.right,
      bottom: renderValues.bottom,
      left: renderValues.left
    };

nextTick(() => {
  console.log(props.dom)
})
watch(props, (n) => {
  renderValues.dom = n.dom;
  renderValues.isTop = n.isTop;
  renderValues.isBottom = n.isBottom;
  renderValues.top = n.top;
  renderValues.right = n.right;
  renderValues.bottom = n.bottom;
  renderValues.left = n.left;
  if (n.dom) {
    let parentEle = n.dom.parentElement, children = parentEle.children;
    let index = 0, preIndex = 0;
    if (children && children.length > 0) {
      for (let child of children) {
        if (child !== n.dom) {
          index++;
        } else {
          break;
        }
      }
      if ((preIndex = index - 1) >= 0) {
        let preEle = children[preIndex];
        if (renderValues.isTop) {
          renderStyle.top = renderValues.top ? preEle.clientHeight + Number(renderValues.top.replace('px', '')) + 'px' : preEle.clientHeight + 'px';
        }
      }
    }
  }
});
</script>

<style lang="less" scoped>
.m-sticky-position {
  position: sticky;
}
</style>